/** 网络请求工具
 * @author HanKaiYang 初始版本
 * @date 2020-6-9 16:47:04
 */
let httpUtilsConfig = wx.getStorageSync('httpUtilsConfig') ? wx.getStorageSync('httpUtilsConfig') : null
if (httpUtilsConfig == null){
    httpUtilsConfig = {
        url: '',
        header: '',
        isLog: false
    }
    wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
}
let isLog = httpUtilsConfig.isLog

/**
 * Config配置目录
 */
const config = new function () {
    /**
     * 设置默认请求地址
     * @param url 请求地址
     * @returns {config}
     */
    this.url = function (url) {
        httpUtilsConfig.url = url
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        return this
    }
    /**
     * 设置默认请求头
     * @param header 请求头
     * @returns {config}
     */
    this.header = function (header) {
        httpUtilsConfig['header'] = header
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        return this
    }
    /**
     * 是否打印请求日志
     * @param isShow
     * @returns {config}
     */
    this.isLog = function (isShow) {
        httpUtilsConfig['isLog'] = isShow
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        httpUtilsConfig = wx.getStorageSync('httpUtilsConfig')
        isLog = httpUtilsConfig.isLog
        return this
    }
    /**
     * 打印当前配置
     */
    this.showConfig = function () {
        httpUtilsConfig = wx.getStorageSync('httpUtilsConfig')
        console.log("当前配置: " + JSON.stringify(httpUtilsConfig))
    }

    /**
     * 清空配置
     */
    this.clear = function () {
        httpUtilsConfig = {
            url: '',
            header: {},
            isLog: false
        }
        wx.removeStorageSync('httpUtilsConfig')
    }
}
/**
 * Config配置项
 */
const httpConfig = function () {
    this.url = function (url) {
        httpUtilsConfig.url = url
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        return this
    }
    this.header = function (header) {
        httpUtilsConfig['header'] = header
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        return this
    }
    this.isLog = function (isShow) {
        httpUtilsConfig['isLog'] = isShow
        wx.setStorageSync('httpUtilsConfig',httpUtilsConfig)
        httpUtilsConfig = wx.getStorageSync('httpUtilsConfig')
        isLog = httpUtilsConfig.isLog
        return this
    }
    /**
     * 打印设置
     */
    this.showConfig = function () {
        httpUtilsConfig = wx.getStorageSync('httpUtilsConfig')
        console.log("当前配置: " + JSON.stringify(httpUtilsConfig))
    }

    /**
     * 清空配置
     */
    this.clear = function () {
        httpUtilsConfig = {
            url: '',
            header: '',
            isLog: false
        }
        wx.removeStorageSync('httpUtilsConfig')
    }
}

/**
 * 请求方法
 * @param url 请求地址
 * @returns {request}
 */
const get = url => {
    return new request('GET',url)
}
const post = url => {
    return new request('POST',url)
}
const put = url => {
    return new request('PUT',url)
}
const del = url => {
    return new request('DELETE',url)
}
const options = url => {
    return new request('OPTIONS',url)
}
const head = url => {
    return new request('HEAD',url)
}
const trace = url => {
    return new request('TRACE',url)
}
const connect = url => {
    return new request('CONNECT',url)
}

const request = function(method,url){
    const that = this
    let requestData = {
        method: method,
        url: url,
        data: {}
    }
    /**
     * 单次请求头部
     * @param header
     * @returns {*}
     */
    this.header = function (header) {
        requestData.header = header
        return this
    }
    /**
     * 单次请求数据
     * @param data
     * @returns {*}
     */
    this.data = function (data) {
        requestData.data = data
        return this
    }
    /**
     * 添加请求数据
     * @param key
     * @param data
     */
    this.addData = function (key,data) {
        requestData.data[key] = data
        return this
    }
    /**
     * 发送请求
     * @returns {promise}
     */
    this.send = function () {
        return new that.promise(requestData.method,requestData.url,requestData.header,requestData.data)
    }

    /**
     * Promise 实现
     * @param method 请求方法
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     * @returns Promise 返回结果
     */
    this.promise = function (method, url, header, data) {
        const _this = this
        let promise = new Promise(((resolve, reject) => {
            //获取网络类型
            wx.getNetworkType({
                success: res => {
                    if (res.networkType !== "none"){
                        if (data === undefined || data == null){
                            data = {}
                        }
                        _this.request(method, url, header, data, resolve,reject)
                    }else {
                        if (isLog){
                            console.log("没有连接到网络")
                        }
                        wx.showToast({
                            title: '网络连接失败',
                            icon: "none",
                            duration: 3000
                        })
                    }
                }
            })
        }))
        /**
         * 请求方法
         * @param method 请求方法 GET,POST,PUT,DELETE
         * @param url 请求地址
         * @param header 可空，为空则默认
         * @param data 请求参数
         * @param resolve 请求成功处理
         * @param reject 请求失败处理
         */
        this.request = function (method, url, header ,data, resolve, reject) {
            //判断url是否完整,完整则请求当前url，不完整则请求默认url
            // httpUtilsConfig = wx.getStorageSync('httpUtilsConfig')
            let baseUrl = httpUtilsConfig.url + url
            if (url.length >= 7){
                let tempUrlA = url.substring(0,8)
                let tempUrlB = url.substring(0,7)
                if (tempUrlA.toLowerCase() === "https://"){
                    baseUrl = url
                }else if (tempUrlB.toLowerCase() === "http://"){
                    baseUrl = url
                }
            }
            //判断是否自定义头部
            let head = header
            if (header === null || header === undefined) {
                head = httpUtilsConfig.header
            }
            if (isLog){
                console.log("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
                console.log('<!------------[ ' + url + ' ]------------------------------------------------')
                console.log("请求方法: " + method)
                console.log("请求地址: " + baseUrl)
                console.log("请求头部: " + JSON.stringify(head))
                console.log("请求参数: " + JSON.stringify(data))
            }

            wx.request({
                method: method,
                url: baseUrl,
                header: head,
                data: data,
                success: res => {
                    if (res.statusCode === 200) {
                        try {
                            if (isLog){
                                console.log("请求结果: " + JSON.stringify(res))
                                console.log('--------------[ ' + url + ' ]------------------------------------------------>')
                                console.log('↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑')
                            }
                            resolve(res)
                        } catch (e) {
                        }
                    } else {
                        if (isLog){
                            console.error("请求结果: " + JSON.stringify(res))
                            console.error('--------------[ ' + url + ' ]------------------------------------------------>')
                        }
                        reject(res)
                    }
                },
                fail: res => reject(res)
            });

        }

        /**
         * 请求成功
         * @param func
         * @returns {*}
         */
        this.success = function (func) {
            promise.then(func)
            return this
        }

        /**
         * 请求失败
         * @param func
         * @returns {*}
         */
        this.fail = function (func) {
            promise.then(null,func)
            return this
        }

        /**
         * 最终结果，成功、失败 都会执行
         * @param func
         */
        this.complete = function (func) {
            promise.then(func,func)
            return this
        }
    }
}

module.exports = {
    config: config,
    get: get,
    post: post,
    put: put,
    delete: del,
    head: head,
    options: options,
    trace: trace,
    connect: connect
}